package com.zky.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.zky.common.to.mq.OrderTo;
import com.zky.common.to.mq.StockLockedTo;
import com.zky.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Description RabbitMq监听
 * @Author 张开源
 * @Date 2022/12/14 22:41
 * @Version 1.0
 **/
@Component
@Slf4j
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    private WareSkuService wareSkuService;

    private static int retryCount = 0;

    /**
     * 手动确认,失败重试需要接受到异常信息,如果必须要try catch 操作,需要在catch里，把异常抛出去，ack拒绝重新入队不能解决无限重试问题。
     *
     * @param stockLockedTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo stockLockedTo, Channel channel, Message message) throws IOException {

        try {
            log.warn("库存锁定收到库存解锁消息：{}", stockLockedTo);
            wareSkuService.unLockedStock(stockLockedTo);
            //死信队列问题未解决，若一条消息重试多次后不再重试，在队列里一直不处理会不会阻塞后续消息消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.warn("库存锁定手动确认消息完毕------------------------------------ack 确认");
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("库存锁定消费异常，e:{},stockLockedTo:{}", e.getLocalizedMessage(), stockLockedTo);
            retryCount++;
            if (retryCount >= 5) {
                //记录消息数据表，后续补偿拒绝不再入队
                retryCount = 0;
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            //有异常，ack拒绝,重新发回队列，重新消费
            throw new RuntimeException("消费异常,msg:" + e.getLocalizedMessage());
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            //log.warn("库存锁定手动确认消息完毕------------------------------------ack 拒绝");
        }

    }


    /**
     * 防止订单服务卡顿，库存服务消息消费了没解锁
     *
     * @param orderTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderClosedRelease(OrderTo orderTo, Channel channel, Message message) throws IOException {

        try {
            log.warn("订单关闭解锁库存消息：{}", orderTo);
            wareSkuService.unLockedStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            log.warn("订单关闭解锁库存手动确认消息完毕------------------------------------ack 确认");
        } catch (Exception e) {
            //有异常，ack拒绝,重新发回队列，重新消费
            log.warn("订单关闭解锁库存消费异常，e:{},stockLockedTo:{}", e.getLocalizedMessage(), orderTo);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            log.warn("订单关闭解锁库存手动确认消息完毕------------------------------------ack 拒绝");
        }

    }
}
